/**
 * Copyright (2017, ) Institute of Software, Chinese Academy of Sciences
 */
package cn.abcsys.cloud.devops.runtime.incubates.models;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import cn.abcsys.cloud.devops.runtime.incubates.utils.UrlUtils;

/**
 * @author wuheng(wuheng@otcaix.iscas.ac.cn)
 * @date   Jul 10, 2017
 *
 */
public class App implements Cloneable {

	protected final static Logger m_logger= Logger.getLogger(App.class); 

	/**
	 * 应用名
	 */
	protected final String name;
	
	/**
	 * 应用运行的环境信息
	 */
	protected final String runtime;
	
	/**
	 * 暴露的端口与Url关系
	 */
	protected final Map<Integer, Url> port2Url = new HashMap<Integer, Url>();
	

	public App(String name, String runtime) {
		super();
		if(!UrlUtils.validIP(runtime) || name == null) {
			throw new RuntimeException("name or runtime is invalid");
		}
		this.name = name;
		this.runtime = runtime;
	}

	/***********************************************************
	 * 
	 *                     Core methods
	 * 
	 **********************************************************/
	
	/**
	 * 为应用添加Url信息
	 *  
	 * @param port
	 * @param url
	 */
	public void addUrl(Integer port, Url url) {
		if(invalid(port, url)) {
			m_logger.info("url or port is invalid");
		} else {
			port2Url.put(port, url);
			m_logger.info("add (" + port + "," + url.toString() + ")");
		}
	}

	/**
	 * 不存在，则返回空
	 * 
	 * @param port
	 * @return
	 */
	public Url getUrl(Integer port) {
		return port2Url.get(port);
	}
	
	
	public String getRuntime() {
		return runtime;
	}

	
	public String getName() {
		return name;
	}

	public Set<Integer> getPorts() {
		return port2Url.keySet();
	}
	
	/***********************************************************
	 * 
	 *                     Other methods
	 * 
	 **********************************************************/
	/**
	 * @param port
	 * @param url
	 * @return
	 */
	private boolean invalid(Integer port, Url url) {
		return (UrlUtils.validPort(port) 
				&& (url != null)) ? false : true;
	}
	
	protected Object clone() throws CloneNotSupportedException {
		App app = (App) super.clone();
		return app;
	}
}
